package com.javaee.thinks.actor;

import com.javaee.thinks.po.ConversationHistory;
import okhttp3.*;
import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.*;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.List;
import java.util.Properties;
import java.util.Scanner;
import java.util.concurrent.TimeUnit; // <-- 添加了这一行导入

public class GeminiOkHttpExample {
    static BufferedReader br;

    static {
        try {
            br = new BufferedReader(new FileReader("C:\\Users\\23619\\Desktop\\tools\\api\\googleApi.txt"));
        } catch (FileNotFoundException e) {
            throw new RuntimeException(e);
        }
    }

    static String apiToken;

    static {
        try {
            apiToken = br.readLine();
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    private static final String CONVERSATION_ID = "current_conversation3"; // 对话 ID
    private SqlSessionFactory sqlSessionFactory;
    public GeminiOkHttpExample() throws IOException {
        try {
            Reader reader = Resources.getResourceAsReader("config/mybatis_config.xml"); // 替换为你的配置文件路径
            sqlSessionFactory = new SqlSessionFactoryBuilder().build(reader);
        } catch (IOException e) {
            throw new RuntimeException("Failed to create SqlSessionFactory", e);
        }
    }

    public static void main(String[] args) throws JSONException, IOException {
        LocalDateTime now_pre = LocalDateTime.now();
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"); // 定义格式
        String now = "此信息发出时间：" + now_pre.format(formatter); // 格式化
        String GEMINI_API_KEY = apiToken;
        final String API_ENDPOINT =
                "https://generativelanguage.googleapis.com/v1beta/models/gemini-2.5-pro-exp-03-25:generateContent?key=" + GEMINI_API_KEY;
        GeminiOkHttpExample geminiExample = new GeminiOkHttpExample();//创建实例启动会话工厂
        Scanner scanner = new Scanner(System.in);

        // --- 修改开始 ---
        // 创建 OkHttpClient 并设置超时时间
        OkHttpClient client = new OkHttpClient.Builder()
                .readTimeout(180, TimeUnit.SECONDS) // 设置读取超时为 3 分钟
                // .connectTimeout(30, TimeUnit.SECONDS) // 如果需要，也可以设置连接超时
                // .writeTimeout(180, TimeUnit.SECONDS)  // 如果需要，也可以设置写入超时
                .build();
        // --- 修改结束 ---

        // 构建请求体
        MediaType mediaType = MediaType.parse("application/json");
        while (true) {
            System.out.print("You: ");
            String userInput = scanner.nextLine() + now;
            if (userInput.equalsIgnoreCase("exit")) {
                break;
            }
            // 从数据库加载对话历史
            List<ConversationHistory> history = geminiExample.loadConversationHistory();
            //------------------------------------------------------------
            // 构建请求体 (包含对话历史)
            JSONArray contents = new JSONArray();
            for (ConversationHistory conversation : history) {
                JSONObject contentObj = new JSONObject();
                contentObj.put("role", conversation.getRole());//contentObj是基本对话单位，循环装入contenArray里
                JSONArray partsArray = new JSONArray();//parts二姐妹
                JSONObject partObj = new JSONObject();//parts二姐妹
                partObj.put("text", conversation.getMessage() + "时间：" + conversation.getTimestamp());//text装partObj
                partsArray.put(partObj);//obj装Array
                contentObj.put("parts", partsArray);//contentObj有两个键值对，role:角色和parts:此角色说的话
                contents.put(contentObj);//contentObj就是单条对话内容的全部信息，装进contents里。
            }
            //------------------------------------------------------------
            // 添加当前的用户输入
            JSONObject userContent = new JSONObject();
            userContent.put("role", "user");
            JSONArray userParts = new JSONArray();
            userParts.put(new JSONObject().put("text", userInput));
            userContent.put("parts", userParts);
            contents.put(userContent);
            //------------------------------------------------------------
            RequestBody body = RequestBody.create(mediaType, new JSONObject().put("contents", contents).toString());
            // 构建请求
            Request request = new Request.Builder()
                    .url(API_ENDPOINT)
                    .post(body)
                    .addHeader("Content-Type", "application/json")
                    .build();
            // 发送请求并获取响应
            try (Response response = client.newCall(request).execute()) { // 第 88 行所在的位置附近
                if (!response.isSuccessful()) {
                    System.err.println("Error: API request failed. Status Code: " + response.code());
                    System.err.println("Response Body:\n" + response.body().string());
                } else {
                    System.out.println("Status Code: " + response.code());
                    String jsonResponse = response.body().string();
                    JSONObject responseJsonObject = new JSONObject(jsonResponse);
                    // --- 安全性检查：检查是否存在 candidates 数组 ---
                    if (!responseJsonObject.has("candidates")) {
                        System.err.println("Warning: Response does not contain 'candidates'. Body:");
                        System.err.println(jsonResponse);
                        // 可以选择跳过此次处理或抛出异常
                        continue;
                    }
                    // --- 安全性检查结束 ---
                    JSONArray candidates = responseJsonObject.getJSONArray("candidates");
                    // --- 安全性检查：检查 candidates 数组是否为空 ---
                    if (candidates.length() == 0) {
                        System.err.println("Warning: 'candidates' array is empty. Body:");
                        System.err.println(jsonResponse);
                        continue;
                    }
                    // --- 安全性检查结束 ---
                    JSONObject firstCandidate = candidates.getJSONObject(0);
                    // --- 安全性检查：检查是否存在 content 对象 ---
                    if (!firstCandidate.has("content")) {
                        System.err.println("Warning: First candidate does not contain 'content'. Candidate:");
                        System.err.println(firstCandidate.toString(2)); // 格式化输出
                        continue;
                    }
                    // --- 安全性检查结束 ---
                    JSONObject content = firstCandidate.getJSONObject("content");
                    // --- 安全性检查：检查是否存在 parts 数组 ---
                    if (!content.has("parts")) {
                        System.err.println("Warning: Content does not contain 'parts'. Content:");
                        System.err.println(content.toString(2));
                        continue;
                    }
                    // --- 安全性检查结束 ---
                    JSONArray parts = content.getJSONArray("parts");
                    // --- 安全性检查：检查 parts 数组是否为空 ---
                    if (parts.length() == 0) {
                        System.err.println("Warning: 'parts' array is empty. Content:");
                        System.err.println(content.toString(2));
                        continue;
                    }
                    // --- 安全性检查结束 ---
                    JSONObject firstPart = parts.getJSONObject(0);
                    // --- 安全性检查：检查是否存在 text 字段 ---
                    if (!firstPart.has("text")) {
                        System.err.println("Warning: First part does not contain 'text'. Part:");
                        System.err.println(firstPart.toString(2));
                        // 可以给一个默认回复或者跳过
                        continue;
                    }
                    // --- 安全性检查结束 ---
                    String modelResponse = firstPart.getString("text");//模型最终回复
                    System.out.println("Gemini: " + modelResponse);
                    // 将用户输入和模型回复存储到数据库
                    geminiExample.storeConversation("user", userInput);
                    geminiExample.storeConversation("model", modelResponse);
                }
                // 第 145 行可能在这里的 catch 块或之后
            } catch (IOException | JSONException e) { // 捕获可能发生的 SocketTimeoutException (属于 IOException)
                // 打印更详细的错误信息，而不是简单地重新抛出 RuntimeException
                System.err.println("An error occurred during the API call or JSON processing: " + e.getMessage());
                e.printStackTrace(); // 打印完整的堆栈跟踪，帮助调试
                // throw new RuntimeException(e); // 如果你确实希望程序在这里终止，可以取消注释这一行
            }

        }
        scanner.close(); // 关闭 Scanner
    }

    // 从数据库加载对话历史
    private List<ConversationHistory> loadConversationHistory() {
        try (SqlSession sqlSession = sqlSessionFactory.openSession()) {
            return sqlSession.selectList("com.javaee.thinks.po.ConversationHistory.getConversationHistory", CONVERSATION_ID);
        }
    }

    // 将对话内容存储到数据库
    private void storeConversation(String role, String message) {
        try (SqlSession sqlSession = sqlSessionFactory.openSession()) {
            ConversationHistory conversation = new ConversationHistory(CONVERSATION_ID, role, message);
            sqlSession.insert("com.javaee.thinks.po.ConversationHistory.insertConversation", conversation);
            sqlSession.commit();
        }
    }
}